<?php

abstract class ScriptAlone_Store_KeyValue extends ScriptAlone_Store {

	protected $key;

	abstract protected function get($key);

	abstract protected function set($key, $dataString);

	abstract protected function delete($key);

	public function __construct($processUidKey) {
		$this->key = $processUidKey;
	}

	/**
	 * @return ScriptAlone_State|null
	 */
	public function getState() {
		$stateString = $this->get($this->key);
		if($stateString) {
			$state = @unserialize($stateString);
			if(!$state || !$state instanceof ScriptAlone_State) {
				$this->delete($this->key);
				throw new Exception('State data is corrupt');
			}
			return $state;
		}
	}

	/**
	 * @param ScriptAlone_State $state
	 * @throws Exception
	 */
	public function saveState(ScriptAlone_State $state) {
		$this->set($this->key, serialize($state));
	}

	public function clearState() {
		$this->delete($this->key);
	}
}
